<?php
namespace app\api\controller;
use think\Cache;
use think\Controller;
use think\Request;
use think\Image;
class Attach extends Controller
{


    //文件上传管理  上传，加水印，缩略图，裁切
    //*+------------------------------------------------------------------------+*/

    //管理上传文件的根目录
	private $_udir='/uploads';
	//商家上传资料
	private $_cmp='/uploads/cmp';
	//允许上传的文件模型     模型值=>array(路径，文件类型,归属)    文件类型 0=>图片  1=>文件  2=>视频      归属 0=>总后台
	private $allow_path_model=array(
			0=>array('dir'=>'image','file'=>0,'host'=>0),   //后台上传图片
			1=>array('dir'=>'file','file'=>1,'host'=>0),    //后台上传文件
			2=>array('dir'=>'video','file'=>2,'host'=>0),   //后台上传视频文件
			3=>array('dir'=>'cmpimg','file'=>0,'host'=>0),  //商家图片
			4=>array('dir'=>'goods','file'=>0,'host'=>0),  //商家图片
	);
	//文件上传格式限制
	private $allow_ext_ary=array();
	//文件上传大小限制
	private $allow_size_ary=array();

    public function initialize(){
		$upload_pic = config('app.UPLOAD_PIC');
		$upload_file= config('app.UPLOAD_FILE');
		$upload_video=config('app.UPLOAD_VIDEO');

		$this->allow_ext_ary = array (
				0 => $upload_pic?$upload_pic:'jpg|png|jpeg|gif',
				1 => $upload_file?$upload_file:array ('zip','rar'),
				2 => $upload_video?$upload_video:array ('flv|mp4'),
		);
		$upload_pic_size = config('app.UPLOAD_PIC_MAXSIZE');
		$upload_file_size= config('app.UPLOAD_FILE_MAXSIZE');
		$upload_video_size=config('app.UPLOAD_VIDEO_MAXSIZE');
		$_mb=1024*1024;
		$this->allow_size_ary = array (
				0 => $upload_pic_size?$upload_pic_size*$_mb:2*$_mb,
				1 => $upload_file_size?$upload_file_size*$_mb:5*$_mb,
				2 => $upload_video_size?$upload_video_size*$_mb:20*$_mb,
		);
    }


    //在线编辑器文件上传
    public function editor() {
        $fun=input('CKEditorFuncNum');
        $type=strtolower(input('type'));

        switch($type){
            case 'image':
                $res=$this->upload(0,'upload');
                break;
            case 'file':
                $res=$this->upload(2,'upload');
                break;
            case 'flash':
                $res=$this->upload(2,'upload');
                break;
        }

        if(0==$res['error']){
            $savepath=$res['url'];
            return "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction({$fun},'$savepath','');</script>";
        }

        return "<script type=\"text/javascript\">window.parent.alert('{$res['message']}');</script>";
    }


    /**
	 * 添加/修改 附件信息
	 * @author leiqianyong 2015-05-04
	 */
	public function edit(Request $request) {
		if(!$request->isPost())return false;
		$module = $request->get("module",0);
		$mark = $_GET['mark'];
		$cid = $_GET['cid'] || 0;
		$mark=empty($mark)?0:1;
		$res = $this->upload($module, 'Filedata',$mark,$cid);
		echo $res ['ret'];
    }


    /**
	 * 上传附件
	 * @param int $type 上传文件模型 决定了文件上传的目录，类型和归属
	 * @param string $file 文件名称 对应控件名称
	 * @param int $mark 是否添加水印  0-否  1-是
	 */
	public function upload($type = 0, $file = '',$mark=0,$cid=0) {
		$model_rtn=$this->allow_path_model[$type];
		if(empty($model_rtn))return false;
		$allow_path = $model_rtn['dir']; //文件路径
		$filetype=$model_rtn['file']; //文件类型
		$allow_ext = $this->allow_ext_ary [$filetype];	//允许上传文件的后缀
		$allow_size = $this->allow_size_ary[$filetype]; //允许上传文件的大小

        //文件目录设置
		$rootPath = $this->_udir."/attach/{$allow_path}";
		if($cid>0)$rootPath = $this->_cmp."/".$cid."/attach/{$allow_path}";
		checkDir('.'.$rootPath);

		//上传操作
		$files = request()->file($file);
		$upload = $files->validate(['size'=>$allow_size,'ext'=>explode('|',$allow_ext)])->move('.'.$rootPath);
		if(!$upload){
			$error = $files->getError();
			$ret='-1,'.$error;
			return ["error" => 1,"message" => $error,'ret'=>$ret];
		}

		//上传成功的操作

		$filename=$rootPath.'/'.str_replace('\\','/',$upload->getSaveName());
        $ext=$upload->getExtension();
        $pinfo=$upload->getInfo();

			//图片添加水印
			$water_img=config('WATERMARK');
            if(0==$filetype && $mark && $water_img){
            	$image =  \think\Image::open('.'.$filename)->water('.'.$water_img,9,50)->save('.'.$filename);
            	// 在图片左上角添加水印（水印文件位于./logo.png） 水印图片的透明度为50 并保存为water.jpg
            }

			//裁切图片 只能裁切 jpe\jpeg\png 格式图片
			$allow_extd = ['jpg','jpeg','png'];
			if(0==$filetype && (1==config('THUMB_IMG_STATUS')) && in_array($ext, $allow_extd)){
				$this->thumb('.'.$filename);
			}

			//超过1M的大图进行压缩处理,gif,png,bmp图片不处理
			$size=$pinfo['size'];
			$deny_extd = ['gif','png','bmp'];
			if(0==$type && (1==config('RAR_PIC_STATUS')) && ($size>config('RAR_PIC_MAXSIZE')*1024*1024) && !in_array($ext, $deny_extd)){
					$image = \think\Image::open('.'.$filename)->save('.'.$filename);
					//不能正确获取压缩后图片大小信息？？？？？？？？？
					$size=filesize('.'.$filename);
			}


			//非图片文件的后缀
			$data ['module'] = $type;
			$data ['path'] = $filename;
			$data ['filext'] = $ext;
			$data ['filesize'] = $size;
			$data ['filename'] = $pinfo['name'];
			$data ['time'] = time();
			$data ['ip'] = request()->ip();
			$data ['type'] = $pinfo['type'];
			$data ['md5'] = $upload->md5();
			$data ['sha1'] = $upload->sha1();
			$data ['cid'] = $cid;
			$data['from']=1;
			$object=model('attach');
			$object->save($data);
			$id = $object->id;
			$ret = $id . ',' . $filename . ',' . $filetype . ',' . $upload->getFilename();
			return  ["error" => 0,"url" => $filename,"ret" => $ret];
	}

    /**
	 * 上传的图片生成缩略图
	 * @param string $filename
	 */
	private function thumb($filename){
        if(!is_file($filename))return false;

		$ext = getImageFormat($filename);

		//gif图片不处理
		if('gif'==$ext){
			return ;
		}
		$image = \think\Image::open($filename);
		$thumb_img = config('THUMB_IMG');
		if(empty($thumb_img)){
			$w=400;
			$h=300;
			$save_path = $filename.'_'.$w.'x'.$h.'.'.$ext;
			$image->thumb($w,$h)->save($save_path);
			return true;
		}

		//根据配置生成多张缩略图片
		foreach($thumb_img as $val){
			$_format=explode('x', $val);
			$save_path = $filename.'_'.$_format[0].'x'.$_format[1].'.'.$ext;
			$image->thumb($_format[0],$_format[1])->save($save_path);
		}
	}




	/**
	 * 裁切图片，只限jpg\jpeg\png 图片
	 * @author leiqianyong 2015-9-3 15:30 PM
	 */
	public function crop(Request $req) {
		$pic= input( 'file' );
		//回调页面对应的图片显示id标志tag_preview,表单位置tag
		$tag= input('tag');
		if ($req->isPost()) {
			$pic = strstr ( $pic, '/Uploads' );
			$x1 = input ( 'x1' );
			$y1 = input ( 'y1' );
			$x2 = input ( 'x2' );
			$y2 = input ( 'y2' );

			$pic_rtn=explode('/', $pic);
			$rootPath = "/Uploads/attach/".$pic_rtn[3]."/".date('Ymd');
			checkDir('.'.$rootPath);
			$pic_ary = pathinfo ( $pic );
			$save_path = $rootPath.'/'.md5($pic_ary ['filename'].'thumb'.NOW_TIME).'.'.$pic_ary ['extension'];


			Image::open ( '.' . $pic )->crop ( $x2 - $x1, $y2 - $y1, $x1, $y1 )->save('.'.$save_path );
			$this->thumb('.'.$save_path);
			$obj=model('attach');
			$where['path']=$pic;
			$pinfo=$obj->field('module')->where($where)->find();
			$data ['module'] = $pinfo['module']?$pinfo['module']:0;
			$data ['path'] = $save_path;
			$data ['filext'] = $pic_ary ['extension'];
			$data ['filename'] = $pic_ary ['filename'].'thumb'.NOW_TIME;
			$data ['time'] = NOW_TIME;
			$data ['ip'] = $req->ip();
			$data['filesize']=filesize('.'.$save_path);
			$data['from']=1;
			$obj->create($data);
			$pic = $save_path;
		}

		//是否是网络数据图片
		$net=0;
		if(0===strpos(strtolower($pic),'http')){
			$net=1;
		}
		//是否是对于后缀内容
		$allow_ext=array('jpg','png','jpeg');
		$allow=0;
		if(in_array(getImageFormat('.'.$pic), $allow_ext)){
			$allow=1;
		}
		$pic_info = getimagesize( '.'.$pic );

		$this->assign('width',$pic_info[0]?$pic_info[0]:0);
		$this->assign('height',$pic_info[1]?$pic_info[1]:0);
		return view("imagecut",compact(['pic','tag','allow','net']));
	}
	/**
	 * 裁切图片，只限jpg\jpeg\png 图片
	 * @author leiqianyong 2015-9-3 15:30 PM
	 */
	public function cmpcrop(Request $req) {
		$cid=input('cid');
		$pic=input('file');
		$size=input('size');
		//回调页面对应的图片显示id标志tag_preview,表单位置tag
		$tag= input('tag');
		if ($req->isPost()) {
			$x1 = $req->post('x1');
			$y1 = $req->post('y1');
			$x2 = $req->post('x2');
			$y2 = $req->post('y2');

			$rootPath = $this->_cmp."/".$cid."/attach/image/".date('Ymd');
			checkDir('.'.$rootPath);
			$pic_ary = pathinfo ( $pic );
			$save_path = $rootPath.'/'.md5($pic_ary ['filename'].'thumb'.NOW_TIME).'.'.$pic_ary ['extension'];

			Image::open( '.' . $pic )->crop ( $x2 - $x1, $y2 - $y1, $x1, $y1 )->save('.'.$save_path );
			$this->thumb('.'.$save_path);
			$obj=model('attach');
			$where['path']=$pic;
			$pinfo=$obj->field('module')->where($where)->find();
			$data ['module'] = $pinfo['module']?$pinfo['module']:0;
			$data ['path'] = $save_path;
			$data ['filext'] = $pic_ary ['extension'];
			$data ['filename'] = $pic_ary ['filename'].'thumb'.NOW_TIME;
			$data ['time'] = NOW_TIME;
			$data ['cid'] =$cid;
			$data ['ip'] = $req->ip();
			$data['filesize']=filesize('.'.$save_path);
			$data['from']=1;
			$obj->add($data);

			$pic = $save_path;
		}

		//是否是网络数据图片
		$net=0;
		if(0===strpos(strtolower($pic),'http')){
			$net=1;
		}
		//是否是对于后缀内容
		$allow_ext=array('jpg','png','jpeg');
		$allow=0;
		if(in_array(getImageFormat('.'.$pic), $allow_ext)){
			$allow=1;
		}
		$pic_info = getimagesize( '.'.$pic );

		$this->assign('width',$pic_info[0]?$pic_info[0]:0);
		$this->assign('height',$pic_info[1]?$pic_info[1]:0);
		return view("imagecrop",compact(['pic','cid','size','tag','allow','net']));
		$this->display ('imagecrop');
	}




    //文件管理页面
    //*+------------------------------------------------------------------------+*/


    /**
     * 附件传输页面
     * @return boolean
     */
    public function plus() {
        $module = input( 'param.module', 0 ); // 模型类型 0-图片 1-文件 2-视频
        $num = input( 'param.num', 1 ); // 附件的数量
        $ext = input( 'param.ext' ); // 可上传的附件后缀
        if (empty ( $ext )) { return false; }
        $size = input( 'param.size', 50 ); // 附件大小M
        $ext_ary = explode ( '|', $ext );
        $this->assign ( 'exty', $ext );
        // foreach ( $ext_ary as &$val ) {
        // 	$val = '*.' . $val;
        // }
        $_ext = implode ( ';', $ext_ary );
        list($ext ,$size,$sizes ,$exty,$exts,$pl_exts) = [$_ext,$size*1024,$size , $ext , implode ( '、', $ext_ary ),implode ( ',', $ext_ary )];
        //后台管理员才有数据库功能
        $tpl='plus';
        /**
        if(is_cookie_login())$tpl='plus';
        $cid=input('param.cid',0);
        if($cid){
            $tpl='pluscmp';
            $this->assign('cid',$cid);
        }
         * **/
        return view($tpl , compact(['ext','module','num','size','sizes','exty','exts',"pl_exts"]));
    }


    //资料库文件管理
    public function search() {
        $module = input( 'module', 0 );
        $map[] = ['module','=',$module];

        //文件名称
        $filename = input('keywords','',trim);
        if($filename) $map[] = ['filename','like','%'.$filename.'%'];
        $this->assign('keywords', $filename );

        //上传时间
        //开始时间
        $starttime = input('starttime');
        if($starttime)$map[]=['time','> time',$starttime];
        $this->assign('starttime',$starttime);

        //结束时间
        $endtime = input('endtime');
        if($endtime)$map[]=['time','<= time',strtotime($endtime)+86400];
        $this->assign('endtime',$endtime);

        //cid商家
        $cid=input('cid');
        if($cid)$map[]=['cid','=',$cid];
        $this->assign('cid',$cid);

        $map[]=['from','=',1];
        $map[]=['state','=',1];
        $field = 'id,filename,path,time,module';
        $pagesize = 8;
        $res = model("attach")->where($map)->field($field)->order('id desc')->paginate($pagesize);

        $this->assign ('list',$res);
        $num=input('num');
        return view("",compact([ 'module','num' ]));
    }


    //后台菜单图标管理
    //*+------------------------------------------------------------------------+*/


    /**
     * 菜单图标选择
     * @param int $page
     * @param int $type 图标类型
     */
    public function icon($type=1,$page=1){
        $pagesize = 80;

        $savefile='save'.$type;
        $savetmp=cache($savefile);

        if($savetmp){
            $files=unserialize($savetmp);
        }else{
            $_ary=array(1=>'/static/common/img/img/');
            $path = $_ary[$type];
            $_files=file_scandir('.'.$path);
            $ext_ary = array('jpg','jpeg','png','gif','bmp');
            foreach($_files as $val){
                $ext = get_extension($val);
                if(!in_array(strtolower($ext),$ext_ary))continue;
                $files[]=$path.$val;
            }
            cache($savefile,serialize($files));
        }

        if ($files) {
            $count=count($files);
            $files = array_slice($files, ($page-1)*$pagesize, $pagesize);
            if(count($files)<$pagesize){
                $this->assign('last_page', 1);
            }
            $this->assign('count',$count);
            $this->assign('files', $files);
            $this->assign('page', $page);
            return $this->fetch();
        }
    }


}
